package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 创建一个函数，用于连接并返回一个Mongo客户端：
func connect() (*mongo.Client, error) {
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))

	if err != nil {
		return nil, err
	}

	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	err = client.Connect(ctx)

	if err != nil {
		return nil, err
	}

	return client, nil
}

// 插入数据
func insertDocument(client *mongo.Client, dbName, colName string, doc interface{}) error {
	collection := client.Database(dbName).Collection(colName)
	_, err := collection.InsertOne(context.Background(), doc)

	return err
}

// 查询数据
func findDocuments(client *mongo.Client, dbName, colName string, filter bson.M) ([]bson.M, error) {
	collection := client.Database(dbName).Collection(colName)

	cur, err := collection.Find(context.Background(), filter)
	if err != nil {
		return nil, err
	}

	var results []bson.M
	err = cur.All(context.Background(), &results)

	return results, err
}

// 更新数据
func updateDocument(client *mongo.Client, dbName, colName string, filter, update bson.M) error {
	collection := client.Database(dbName).Collection(colName)
	_, err := collection.UpdateMany(context.Background(), filter, bson.M{
		"$set": update,
	})

	return err
}

func main() {
	client, err := connect()
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(context.Background())

	// 插入文档
	doc := bson.M{"username": "testuser", "email": "testuser@example.com", "age": 25}
	err = insertDocument(client, "mydb", "users", doc)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("插入文档成功")

	// 查询文档
	filter := bson.M{"username": "testuser"}
	docs, err := findDocuments(client, "mydb", "users", filter)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("查询结果：", docs)

	// 更新文档
	update := bson.M{"email": "updated_email@example.com", "age": 26}
	err = updateDocument(client, "mydb", "users", filter, update)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("更新文档成功")

	// 查询更新后的文档
	docs, err = findDocuments(client, "mydb", "users", filter)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("更新后的查询结果：", docs)

}
